package com.hzw.saas.common.config.configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.hzw.saas.common.util.constants.PatternConsts;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.annotation.Bean;

/**
 * Jackson时间格式化通用配置
 * 生效需求：
 * 1. 未使用@JsonFormat注解的Date和LocalDateTime字段
 * 2. mvc请求为application/json
 *
 * @author zzl
 * @since 05/10/2021
 */
@JsonComponent
public class DateFormatConfig {

    private final String pattern = PatternConsts.NORM_DATETIME_PATTERN;

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {

        return builder -> {
            builder.failOnEmptyBeans(false)
                .failOnUnknownProperties(false)
                .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .simpleDateFormat(pattern)
                .serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)))
                .deserializerByType(LocalDateTime.class, new MyDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern)));
        };
    }

}
